/**
 * Ingenius-Group S.A.S
 * Project: SAU
 * File: Role.java
 * Date: 17/11/2010
 */

package com.ingenius.sau.shared.model.users;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.jdo.annotations.Element;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.FetchGroup;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NullValue;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.ingenius.sau.shared.model.core.BaseBean;

/**
 * Class <strong>Role</strong>
 * 
 * @author Jesus David
 * @version 0.1
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
@FetchGroup(name = "with_users", members = { @Persistent(name = "users") })
public class Role implements BaseBean {

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
	private String id;

	@Persistent(nullValue = NullValue.NONE)
	private String name;

	@Persistent(nullValue = NullValue.NONE)
	private String description;

	@Persistent
	private List<String> privileges;

	@Persistent(mappedBy = "role")
	@Element(dependent = "true")
	private List<User> users;

	// CONSTRUCTORS

	public Role() {
	}

	public Role(String id) {
		this.id = id;
	}

	// METHODS

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public List<String> getPrivileges() {
		return (privileges == null) ? privileges = new LinkedList<String>()
				: privileges;
	}

	public void setPrivileges(List<String> privileges) {
		this.privileges = privileges;
	}

	public List<User> getUsers() {
		return (users == null) ? users = new ArrayList<User>() : users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public void addUser(User user) {
		getUsers().add(user);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Role) {
			return ((Role) obj).getId().equals(id);
		}
		return false;
	}

	public Role toDTO() {
		if (this != null) {
			this.setUsers(null);
		}
		return this;
	}
}
